import configparser
import os


class ConfigManager:
    def __init__(self, config_path="config.ini"):
        self.config_path = config_path
        self.config = configparser.ConfigParser()
        self._load()

    def _load(self):
        if os.path.exists(self.config_path):
            self.config.read(self.config_path, encoding="utf-8")
        else:
            self._init_default()

    def reload(self):
        """强制重新从文件加载配置"""
        self.config = configparser.ConfigParser()
        self._load()

    def _init_default(self):
        # 初始化位移台设置
        self.config["stage:x"] = {
            "start": "0.0",
            "end": "5.0",
            "vmax": "2.0",
            "acc": "2.0",
            "step": "1000.0"
        }
        self.config["stage:y"] = {
            "start": "0.0",
            "end": "5.0",
            "vmax": "2.0",
            "acc": "2.0",
            "step": "1000.0"
        }

        # 初始化源表设置
        self.config["source"] = {
            "voltage": "1.0",
            "limit": "0.01",
            "samples": "3",
            "interval": "500"
        }

        # 初始化存储设置（包括图像配置）
        self.config["storage"] = {
            "data_path": "./result/data",
            "image_path": "./result/pic",
            "file_format": "csv",
            "image_format": "png",  # 默认值改为小写
            "interpolation_algorithm": "none",
            "color_map": "jet",
            "refresh_interval": "1",         # 图像刷新频率（秒）
            "vmin": "-1",                # 热图下限（-1 表示自动）
            "vmax": "-1"                 # 热图上限（-1 表示自动）
        }
        self.config["global"] = {
            "language": "zh_CN"  # 比如默认中文
        }
        self.save()
    def get_global_config(self):
        if "global" not in self.config:
            self.config["global"] = {}
            self.save()
        return dict(self.config["global"])

    def get_language(self):
        # 如果没有 global 段，就初始化一个
        if "global" not in self.config:
            self.config["global"] = {}
            self.config["global"]["language"] = "zh_CN"  # 默认中文
            self.save()
        return self.config["global"].get("language", "zh_CN")

    def set_language(self, lang_code: str):
        if "global" not in self.config:
            self.config["global"] = {}
        self.config["global"]["language"] = lang_code
        self.save()


    # ======================= 位移台 =======================
    def get_stage_axis_config(self, axis):
        section = f"stage:{axis}"
        if section not in self.config:
            self._init_default()
        return {
            "start": float(self.config[section].get("start", "0.0")),
            "end": float(self.config[section].get("end", "10.0")),
            "vmax": float(self.config[section].get("vmax", "2.0")),
            "acc": float(self.config[section].get("acc", "2.0")),
            "step": float(self.config[section].get("step", "1.0"))
        }

    def set_stage_axis_config(self, axis, data: dict):
        section = f"stage:{axis}"
        self.config[section] = {
            "start": str(data["start"]),
            "end": str(data["end"]),
            "vmax": str(data["vmax"]),
            "acc": str(data["acc"]),
            "step": str(data["step"])
        }
        self.save()

    # ======================= 源表 =======================
    def get_source_config(self):
        section = "source"
        if section not in self.config:
            self._init_default()
        return {
            "voltage": float(self.config[section].get("voltage", "1.0")),
            "limit": float(self.config[section].get("limit", "0.01")),
            "samples": int(self.config[section].get("samples", "3")),
            "interval": int(self.config[section].get("interval", "500"))
        }

    def set_source_config(self, data: dict):
        section = "source"
        self.config[section] = {
            "voltage": str(data["voltage"]),
            "limit": str(data["limit"]),
            "samples": str(data["samples"]),
            "interval": str(data["interval"])
        }
        self.save()

    # ======================= 存储设置（含图像设置） =======================
    def get_storage_config(self):
        section = "storage"
        if section not in self.config:
            self._init_default()
        return {
            "data_path": self.config[section].get("data_path", "./result/data"),
            "image_path": self.config[section].get("image_path", "./result/pic"),
            "file_format": self.config[section].get("file_format", "csv").lower(),
            "image_format": self.config[section].get("image_format", "png").lower(),
            "interpolation_algorithm": self.config[section].get("interpolation_algorithm", "none").lower(),
            "color_map": self.config[section].get("color_map", "jet").lower(),
            "refresh_interval": int(self.config[section].get("refresh_interval", "1")),
            "vmin": float(self.config[section].get("vmin", "-1")),
            "vmax": float(self.config[section].get("vmax", "-1")),
        }

    def set_storage_config(self, data: dict):
        section = "storage"
        self.config[section] = {
            "data_path": data["data_path"],
            "image_path": data["image_path"],
            "file_format": data["file_format"],
            "image_format": data["image_format"],
            "interpolation_algorithm": data["interpolation_algorithm"],
            "color_map": data["color_map"],
            "refresh_interval": str(data.get("refresh_interval", 1)),
            "vmin": str(data.get("vmin", -1)),
            "vmax": str(data.get("vmax", -1))
        }
        self.save()

    def save(self):
        with open(self.config_path, "w", encoding="utf-8") as f:
            self.config.write(f)
